<?php

namespace App\Http\Controllers\admin;

use App\Models\Article;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ArticleController extends Controller
{
    public function __construct()
    {
        view()->share('menu','article');
    }

    /**
     * 文章列表
     * @author: yanggang
     * @date: 2018/4/12 0012
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        $list = Article::orderBy('id','DESC')->paginate(15);
        foreach ($list as $key=>$item){
            $list[$key]['content'] = mb_substr($item['content'],0,30); //显示前30个字符
        }
        $page_num = $list->firstItem();
        return view('admin/article/index',compact('list','page_num'));
    }

    /**
     * 添加文章
     * @author: yanggang
     * @date: 2018/4/12 0012
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function create()
    {
        return view('admin/article/create');
    }

    /**
     * 文章数据写进数据库
     * @author: yanggang
     * @date: 2018/4/12 0012
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(Request $request)
    {
        $title = $request->get('title');
        $content = $request->get('content');
        if (empty($title)){
            return back()->with(['msg'=>'文章标题不能为空','status'=>0]);
        }
        if (empty($content)){
            return back()->with(['msg'=>'文章内容不能为空','status'=>0]);
        }

        Article::create(['title'=>$title,'content'=>$content]);
        return back()->with(['msg' => '添加成功', 'status' => 1, 'msg_url' => '/admin/article']);

        exit();
    }

    /**
     * 编辑文章
     * @author: yanggang
     * @date: 2018/4/12 0012
     * @param Request $request
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function edit(Request $request,$id)
    {
        $list = Article::find($id);
        return view('admin/article/edit',compact('list'));
    }

    /**
     * 编辑文章写进数据库
     * @author: yanggang
     * @date: 2018/4/12 0012
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request, $id)
    {
        $title = $request->get('title');
        $content = $request->get('content');
        if (empty($title)){
            return back()->with(['msg'=>'文章标题不能为空','status'=>0]);
        }
        if (empty($content)){
            return back()->with(['msg'=>'文章内容不能为空','status'=>0]);
        }

        Article::where(['id'=>$id])->update(['title'=>$title,'content'=>$content]);
        return back()->with(['msg' => '更新成功', 'status' => 1, 'msg_url' => '/admin/article']);
    }

    public function destroy(Request $request,$id)
    {
        Article::destroy($id);
        return back()->with(['msg' => '删除成功', 'status' => 1, 'msg_url' => '/admin/article']);

    }
}
